import BaseComponent from "./BaseComponent";
import {Button as AntButton, Checkbox, Radio, Select} from "antd";
import React from "react";
import SysDataPresenter from "../../.gen/presenter/SysDataPresenter";

export default class RSelect extends BaseComponent {

    static defaultProps = {
        dictCode: undefined,
        model: '',
        type:'select'
    };

    constructor(props) {
        super(props);
        this.state = {
            dictOptions: []
        }
        this.presenter = new SysDataPresenter(this);
        let dictCode = this.props.dictCode;
        if (dictCode && !this.props.children) {
            this.loadDictOptions(dictCode);
        }
    }

    // 根据字典code查询字典项
    loadDictOptions(dictCode) {
        this.presenter.findDictionaryList({dictCode: dictCode, model: this.props.model}, undefined, (res) => {
            if (res.code === 0) {
                let dictOptions = res.data.map(item => ({
                    value: this.props.dictValue ? item['' + this.props.dictValue] : item.dicValue,
                    label: this.props.dictText ? item['' + this.props.dictText] : item.dicName
                }))
                this.setState({dictOptions: dictOptions});
            } else {
                console.error('getDictItems error: : ', res)
            }
        })
    }

    render() {
        let {dictOptions} = this.state;
        let props = {...this.props};
        let {type} = this.props
        delete props.dictCode;
        delete props.dictTable;
        delete props.type;
        return (
            type==='select'?<Select
                {...props}
                showSearch
                optionFilterProp="children"
                filterOption={(input, option) =>
                    option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                }
            >
                {
                    this.props.children ? this.props.children :
                        dictOptions.map(((item, index) => {
                            return <Select.Option key={index} data={item}
                                                  value={item.value}>{item.text || item.label}</Select.Option>
                        }))
                }
            </Select>:type==='radio'?<Radio.Group
                {...props}>
                {
                    this.props.children?this.props.children:
                        dictOptions.map(((item,index) => {
                            return <Radio key={index} data={item} value={item.value}>{item.text || item.label}</Radio>
                        }))
                }
            </Radio.Group>:type==='checkbox'? <Checkbox.Group
                {...props}
                options={dictOptions}
            >
            </Checkbox.Group>:null
        )
    }
}